package cn.com.acca.ma.service.impl;

import cn.com.acca.ma.common.util.DateUtil;
import cn.com.acca.ma.common.util.PropertiesUtil;
import cn.com.acca.ma.constant.RobotPrintBuySellSuggestionFormat;
import cn.com.acca.ma.model.Robot6StockTransactRecord;
import cn.com.acca.ma.service.Robot6EtfTransactRecordService;

import java.util.List;

public class Robot6EtfTransactRecordServiceImpl extends BaseServiceImpl<Robot6EtfTransactRecordServiceImpl, Robot6StockTransactRecord> implements
        Robot6EtfTransactRecordService {

    /**
     * 执行某段时间内的股票买卖交易（etf四种算法最近12年中平均收益率最高的）
     */
    @Override
    public void doBuyAndSellByBeginDateAndEndDate_etf12YearHighestAverageProfitRate() {
        logger.info("执行某段时间内的etf买卖交易（etf四种算法最近12年中平均收益率最高的）");

        String beginDate = PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.etf12YearHighestAverageProfitRate.beginDate");
        String endDate = PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.etf12YearHighestAverageProfitRate.endDate");
        Integer maxHoldEtfNumber = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.etf12YearHighestAverageProfitRate.maxHoldEtfNumber"));
        Integer holdShippingSpaceType = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.etf12YearHighestAverageProfitRate.holdShippingSpaceType"));
        Integer mdlEtfType = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.etf12YearHighestAverageProfitRate.mdlEtfType"));
        Integer beforeYear = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.etf12YearHighestAverageProfitRate.beforeYear"));
        Boolean maNotDecreasingEnable = Boolean.parseBoolean(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.etf12YearHighestAverageProfitRate.ma.not.decreasing.enable"));
        String maNotDecreasingLevel = PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.etf12YearHighestAverageProfitRate.ma.not.decreasing.level");
        String maNotDecreasingDateNumber = PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.etf12YearHighestAverageProfitRate.ma.not.decreasing.dateNumber");
        Double closePriceStart = Double.parseDouble(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.etf12YearHighestAverageProfitRate.closePrice.start"));
        Double closePriceEnd = Double.parseDouble(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.etf12YearHighestAverageProfitRate.closePrice.end"));
        Integer xrDateNumber = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.etf12YearHighestAverageProfitRate.xr.dateNumber"));
        Integer mandatoryStopLoss = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.etf12YearHighestAverageProfitRate.mandatoryStopLoss"));
        Double mandatoryStopLossRate = Double.parseDouble(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.etf12YearHighestAverageProfitRate.mandatoryStopLossRate"));
        Integer printFormat = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.etf12YearHighestAverageProfitRate.print.format"));

        // 获取日期列表
        List<String> dateList = etfTransactionDataDao.findDistinctDateBetweenBeginDateAndEndDate(beginDate, endDate);
        if (null != dateList && dateList.size() > 0) {
            for (int i = 0; i < dateList.size(); i++) {
                String currentDate = dateList.get(i);
                Integer holdEtfNumber;

                /*************************************** 卖etf ***********************************************/
                // 更新robot6_account表
                robot6AccountDao.updateRobotAccountBeforeSellOrBuy(currentDate);

                // 卖etf
                robot6EtfTransactRecordDao.sellOrBuy(currentDate, mandatoryStopLoss, mandatoryStopLossRate, mdlEtfType);

                // 更新robot6_account表
                robot6AccountDao.updateRobotAccountAfterSellOrBuy(currentDate);

                // 如果所有账号都已经满仓，则跳过这个交易日
                if (isFullEtfInRobot6Account(maxHoldEtfNumber)) {
                    logger.warn("所有账号都是满仓，因此日期【" + currentDate + "】不做任何交易，直接跳过");

                    // 更新robot6_account表的total_assets字段
                    robot6AccountDao.updateRobotAccountAfterBuyOrSell(currentDate);

                    continue;
                }

                /*************************************** 准备数据 ***********************************/
                String lastDate = etfTransactionDataDao.findLatestDate(DateUtil.lastDate(currentDate));
                String lastYear = etfTransactionDataDao.findLatestDate(DateUtil.beforeYear(lastDate, beforeYear));
                String xrEndDate = etfTransactionDataDao.findNextDate(DateUtil.nextDate(currentDate, xrDateNumber));
                if (null != lastDate && null != lastYear){
                    logger.info("当前交易日【" + currentDate +"】的前一日是【" + lastDate + "】，对应的前一年是【" + lastYear + "】");
                } else {
                    logger.warn("当前交易日【" + currentDate +"】的前一日是【" + lastDate + "】，对应的前一年是【" + lastYear + "】，不符合要求，不做交易");

                    // 更新robot6_account表的total_assets字段
                    robot6AccountDao.updateRobotAccountAfterBuyOrSell(currentDate);

                    continue;
                }

                List<String> codeList = etfTransactionDataDao.findDistinctDateByDateAndLessThanMinDate(lastYear, lastDate);
                if (codeList.size() == 0){
                    logger.warn("符合条件的记录数为0，当前日期是【" + currentDate + "】，不做交易");

                    // 更新robot6_account表的total_assets字段
                    robot6AccountDao.updateRobotAccountAfterBuyOrSell(currentDate);

                    continue;
                }

                // 清空robot6_stock_filter表
                robot6EtfFilterDao.truncateTableRobotEtfFilter();
                // 根据code列表，向robot6_stock_filter表中插入etf代码，不包括已经买入的
                robot6EtfFilterDao.insertBullEtfCodeFromEtfTransactionDataByCodeList(codeList);

                /*************************************** 按照条件，过滤etf ***********************************/
                if (maNotDecreasingEnable){
                    // 过滤条件：MA不单调递减，过滤股票
                    String[] maLevelArray = maNotDecreasingLevel.replace("[", "").replace("]", "").split(",");
                    String[] dateNumberArray = maNotDecreasingDateNumber.replace("[", "").replace("]", "").split(",");
                    for (int j=0; j<maLevelArray.length && j<dateNumberArray.length; j++){
                        String maLevel = maLevelArray[j].trim();
                        String dateNumber = dateNumberArray[j].trim();
                        robot6EtfFilterDao.filterByMANotDecreasing(currentDate, Integer.parseInt(maLevel), dateNumber);
                    }
                }

                // 只保留这个价格区间以内的股票
                robot6EtfFilterDao.filterByLessThanClosePrice(currentDate, closePriceStart, closePriceEnd);
                // 过滤条件：删除收盘价小于250均线的ETF
//                robot6EtfFilterDao.filterClosePriceLessThanMA(currentDate);
                // 过滤条件：删除除过权的股票
                robot6EtfFilterDao.filterByXr(currentDate, xrEndDate);

                /************************** 判断使用哪种算法，判断今天是否是交易日 ***************************/
                // 过滤条件：更新robot6_stock_filter表：direction为1；filter_type为交易算法；accumulative_profit_rate累计收益。单位：元
                robot6EtfFilterDao.updateRobotEtfFilter(currentDate);
                // 过滤条件：从robot6_stock_filter表中删除那些不是交易日的记录
                robot6EtfFilterDao.filterByBuyDate(currentDate, mdlEtfType);

                /*************************************** 买etf ******************************************/
                // 买
                robot6EtfTransactRecordDao.buyOrSell(currentDate, maxHoldEtfNumber, holdShippingSpaceType);

                // 更新robot6_account表的total_assets字段
                robot6AccountDao.updateRobotAccountAfterBuyOrSell(currentDate);

                // 获取买卖建议
                String printText = null;
                if (printFormat.equals(RobotPrintBuySellSuggestionFormat.JSON)) {
                    // json方式
                    printText = super.printBuySellSuggestionByJson_etf12YearHighestAverageProfitRate(currentDate);
                }
                if (printFormat.equals(RobotPrintBuySellSuggestionFormat.SIMPLE)) {
                    // 简单文本格式
                    printText = super.printBuySellSuggestionBySimple_etf12YearHighestAverageProfitRate(currentDate);
                }
                logger.info("买卖建议：\n" + printText);
            }
        }

        logger.info("执行某段时间内的etf买卖交易完成（etf四种算法最近12年中平均收益率最高的）");
    }

    @Override
    public String listToString(List list) {
        return null;
    }
}
